import app from 'electron'
import is from 'electron-is'
import fs from 'fs';
import path from 'path';


var net = undefined
if (is.main()) {
	net = app.net;
} else {
	net = app.remote.net;
}

/**
 * 在文件管理器中加载网站类别列表
 */
function loadApplicationCategoriesByFile(filePath) {
	return fs.readFileSync(filePath).toString();
}

/**
 * 请求基础方法
 * 
 * @param {Object} url
 * @param {Object} sucfunc
 * @param {Object} errfunc
 */
function requestBase(url, sucfunc, errfunc) {

	var request = net.request(url)
	request.chunkedEncoding = false;

	var data = ""
	// 监听响应
	request.on('response', (response) => {
		// 返回状态码
		console.log(response.statusCode);
		// 返回请求头
		console.log(response.headers);

		if (response.statusCode !== 200) {
			errfunc(response);
		}
		response.on('data', (data_frame) => {
			// 获取返回数据
			data += data_frame.toString();
		})
	})

	request.on('finish', () => {
		setTimeout(() => {
			console.log("data", data);
			sucfunc(data);
			data = ""
		}, 500);
	})
	// 结束请求, 不结束无法返回数据
	request.end();
}

export default {
	requestBase,
	loadApplicationCategoriesByFile
}
